﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Bxm.Service.Dto;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using AngleSharp.Dom;
using DocumentFormat.OpenXml.Office.CustomUI;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace Admin.NET.Application.Bxm.Service;

/// <summary>
/// 保单查询服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class BaodanEntityService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<BaodanEntity> _baodanEntityRep;
    public BaodanEntityService(SqlSugarRepository<BaodanEntity> baodanEntityRep)
    {
        _baodanEntityRep = baodanEntityRep;
    }

    /// <summary>
    /// 分页查询保单查询
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询保单查询")]
    public async Task<SqlSugarPagedList<BaodanEntityOutput>> Page(PageBaodanEntityInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        var query = _baodanEntityRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.EffectiveDate.Contains(input.SearchKey)
                || u.CompanyName.Contains(input.SearchKey)
                || u.ProductName.Contains(input.SearchKey)
                || u.ProductNumber.Contains(input.SearchKey)
                || u.Policyholder.Contains(input.SearchKey)
                || u.PhoneNumber.Contains(input.SearchKey)
                || u.Cycle.Contains(input.SearchKey)
                || u.Contact.Contains(input.SearchKey)
                || u.Status.Contains(input.SearchKey)
                || u.Remark.Contains(input.SearchKey)
                || u.Rate.Contains(input.SearchKey)
                || u.TeamCost.Contains(input.SearchKey)
                || u.JJCompany.Contains(input.SearchKey)
                || u.Xjcz.Contains(input.SearchKey)
                || u.Gssrqk.Contains(input.SearchKey)
                || u.Srbl.Contains(input.SearchKey)
                || u.Gszcqk.Contains(input.SearchKey)
                || u.Zcbl.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.EffectiveDate), u => u.EffectiveDate.Contains(input.EffectiveDate.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CompanyName), u => u.CompanyName.Contains(input.CompanyName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProductName), u => u.ProductName.Contains(input.ProductName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProductNumber), u => u.ProductNumber.Contains(input.ProductNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Policyholder), u => u.Policyholder.Contains(input.Policyholder.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PhoneNumber), u => u.PhoneNumber.Contains(input.PhoneNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Cycle), u => u.Cycle.Contains(input.Cycle.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Status), u => u.Status.Contains(input.Status.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Rate), u => u.Rate.Contains(input.Rate.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TeamCost), u => u.TeamCost.Contains(input.TeamCost.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.JJCompany), u => u.JJCompany.Contains(input.JJCompany.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Xjcz), u => u.Xjcz.Contains(input.Xjcz.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Gssrqk), u => u.Gssrqk.Contains(input.Gssrqk.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Srbl), u => u.Srbl.Contains(input.Srbl.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Gszcqk), u => u.Gszcqk.Contains(input.Gszcqk.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Zcbl), u => u.Zcbl.Contains(input.Zcbl.Trim()))
            .Select<BaodanEntityOutput>();
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加保单查询
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加保单查询")]
    public async Task<long> Add(AddBaodanEntityInput input)
    {
        var entity = input.Adapt<BaodanEntity>();
        await _baodanEntityRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除保单查询
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除保单查询")]
    public async Task Delete(DeleteBaodanEntityInput input)
    {
        var entity = await _baodanEntityRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        //await _baodanEntityRep.FakeDeleteAsync(entity);   //假删除
        await _baodanEntityRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除保单
    /// </summary>
    /// <param name="outputs"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "BatchDelete")]
    [DisplayName("批量删除保单")]
    public async Task BatchDelete(BaodanEntityOutput[] outputs)
    {
        foreach(var item in outputs)
        {
            var entity = item.Adapt<BaodanEntity>();
            await _baodanEntityRep.DeleteAsync(entity);
        }
    }

    /// <summary>
    /// 更新保单查询
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新保单查询")]
    public async Task Update(UpdateBaodanEntityInput input)
    {
        var entity = input.Adapt<BaodanEntity>();
        await _baodanEntityRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取保单查询
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取保单查询")]
    public async Task<BaodanEntity> Detail([FromQuery] QueryByIdBaodanEntityInput input)
    {
        return await _baodanEntityRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取保单查询列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取保单查询列表")]
    public async Task<List<BaodanEntityOutput>> List([FromQuery] PageBaodanEntityInput input)
    {
        return await _baodanEntityRep.AsQueryable().Select<BaodanEntityOutput>().ToListAsync();
    }

    /// <summary>
    /// 导出
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Export")]
    [DisplayName("导出")]
    public async Task<IActionResult> ExportBaodan(PageBaodanEntityInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        var baodanList = await _baodanEntityRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.EffectiveDate.Contains(input.SearchKey)
                || u.CompanyName.Contains(input.SearchKey)
                || u.ProductName.Contains(input.SearchKey)
                || u.ProductNumber.Contains(input.SearchKey)
                || u.Policyholder.Contains(input.SearchKey)
                || u.PhoneNumber.Contains(input.SearchKey)
                || u.Cycle.Contains(input.SearchKey)
                || u.Contact.Contains(input.SearchKey)
                || u.Status.Contains(input.SearchKey)
                || u.Remark.Contains(input.SearchKey)
                || u.Rate.Contains(input.SearchKey)
                || u.TeamCost.Contains(input.SearchKey)
                || u.JJCompany.Contains(input.SearchKey)
                || u.Xjcz.Contains(input.SearchKey)
                || u.Gssrqk.Contains(input.SearchKey)
                || u.Srbl.Contains(input.SearchKey)
                || u.Gszcqk.Contains(input.SearchKey)
                || u.Zcbl.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.EffectiveDate), u => u.EffectiveDate.Contains(input.EffectiveDate.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CompanyName), u => u.CompanyName.Contains(input.CompanyName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProductName), u => u.ProductName.Contains(input.ProductName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProductNumber), u => u.ProductNumber.Contains(input.ProductNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Policyholder), u => u.Policyholder.Contains(input.Policyholder.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PhoneNumber), u => u.PhoneNumber.Contains(input.PhoneNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Cycle), u => u.Cycle.Contains(input.Cycle.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Status), u => u.Status.Contains(input.Status.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Rate), u => u.Rate.Contains(input.Rate.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TeamCost), u => u.TeamCost.Contains(input.TeamCost.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.JJCompany), u => u.JJCompany.Contains(input.JJCompany.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Xjcz), u => u.Xjcz.Contains(input.Xjcz.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Gssrqk), u => u.Gssrqk.Contains(input.Gssrqk.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Srbl), u => u.Srbl.Contains(input.Srbl.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Gszcqk), u => u.Gszcqk.Contains(input.Gszcqk.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Zcbl), u => u.Zcbl.Contains(input.Zcbl.Trim()))
            .Select<BaodanEntityExport>().ToListAsync();

        IExcelExporter excelExporter = new ExcelExporter();
        var res = await excelExporter.ExportAsByteArray(baodanList);
        return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = "保单明细" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx" };

    }
    /// <summary>
    /// 下载模板
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "DownloadTemplate")]
    [DisplayName("下载模板")]
    public async Task<IActionResult> DownloadTemplate()
    {
        return await CommonUtil.ExportExcelTemplate<BaodanEntityImport>("保单导入模板");
    }

    /// <summary>
    /// 导入
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "import")]
    [DisplayName("导入")]
    public async Task<int> Import([Required] IFormFile file)
    {
        var data = await CommonUtil.ImportExcelData<BaodanEntityImport>(file);

        var entitys = new List<BaodanEntity>();
        foreach (var item in data)
        {

            //查找是否已经存在
            var isExit = await _baodanEntityRep.GetFirstAsync(u => u.ProductNumber == item.ProductNumber);


            if (isExit != null)
            {
                var id = isExit.Id;

                isExit = item.Adapt<BaodanEntity>();
                isExit.Id = id;

                await _baodanEntityRep.AsUpdateable(isExit).IgnoreColumns(ignoreAllNullColumns: false).ExecuteCommandAsync();
            }
            else 
            {
                var entity = item.Adapt<BaodanEntity>();

                entitys.Add(entity);
            }
            
        }
        await _baodanEntityRep.InsertRangeAsync(entitys);
        return data.Count;
    }
}
